#!/bin/bash
# SPDX-License-Identifier: MulanPSL-2.0+
# Copyright (c) 2020 Huawei Technologies Co., Ltd. All rights reserved.

[[ $CCI_SRC ]] || CCI_SRC=/c/compass-ci

. $CCI_SRC/lib/check_public_network.sh


for gem_source in $(gem sources -l | grep http)
do
	gem source -r $gem_source
done
gem source -a em sources --add https://mirrors.tuna.tsinghua.edu.cn/rubygems/ -u
gem install --no-user-install git:1.9.1 faye-websocket:0.11.1 rest-client:2.1.0 cucumber:7.1.0 \
	json:2.6.1 elasticsearch:7.11.1 bunny:2.19.0 nokogiri:1.12.5 ruby-libvirt:0.8.0


grep -q '^lkp:' /etc/passwd || useradd -u 1090 lkp
grep -q '^mailer:' /etc/passwd || useradd -u 1144 mailer
grep -q '^team:' /etc/group || groupadd team
grep -q '^committer:' /etc/group || groupadd -g 1999 committer

sed -i '/^net.ipv4.ip_forward=/d' /etc/sysctl.conf
sed -i '/^net.ipv6.bindv6only=/d' /etc/sysctl.conf
sed -i '/^vm.max_map_count=/d' /etc/sysctl.conf
sed -i '/^net.ipv4.ip_local_port_range/d' /etc/sysctl.conf

cat >> /etc/sysctl.conf <<EOF
net.ipv4.ip_forward=1
net.ipv6.bindv6only=1
vm.max_map_count=262144
net.ipv4.ip_local_port_range = 32000 65535
EOF

sysctl -p

[[ -f /etc/modules-load.d/nfs ]] && {
	sed -i '/^nfs$/d' /etc/modules-load.d/nfs
	sed -i '/^nfsd$/d' /etc/modules-load.d/nfs
}

cat >> /etc/modules-load.d/nfs <<EOF
nfs
nfsd
EOF

[[ -f /etc/modules-load.d/cifs ]] && {
	sed -i '/^cifs$/d' /etc/modules-load.d/cifs
}

cat >> /etc/modules-load.d/cifs <<EOF
cifs
EOF

server_ip=$(ip route get 1.2.3.4 | awk '{print $7; exit}')

: ${DOCKER_REGISTRY_HOST:=$server_ip}
: ${DOCKER_REGISTRY_PORT:=5001}
cat > /etc/docker/daemon.json <<EOF
{
  "log-driver": "fluentd",
  "log-opts":{
    "fluentd-address": "localhost:24225",
    "fluentd-async-connect": "true",
    "tag": "{{.Name}}"
  },
  "registry-mirrors": [
    "https://hub-mirror.c.163.com",
    "https://docker.mirrors.ustc.edu.cn"
  ],
  "insecure-registries": ["$DOCKER_REGISTRY_HOST:$DOCKER_REGISTRY_PORT"]
}
EOF

sed -i '/^Environment=/a\TimeoutSec=0' /usr/lib/systemd/system/docker.service

mkdir -p /etc/systemd/system/docker.service.d
cat >/etc/systemd/system/docker.service.d/10-ramdisk.conf <<EOF
[Service]
Environment=DOCKER_RAMDISK=true
EOF

docker_load_images()
{
	images_dir=/tmp/docker_images

	mkdir -p $images_dir
	wget -q -O $images_dir/docker_list https://repo.oepkgs.net/openEuler/compass-ci/cci-deps/docker/$(arch)/docker_list || return 1
	while read line
	do
		(
			wget -q -O $images_dir/$line https://repo.oepkgs.net/openEuler/compass-ci/cci-deps/docker/$(arch)/$line || return 1
			docker load -q -i $images_dir/$line
		) &
	done < $images_dir/docker_list
	wait
	rm -rf $images_dir
}

systemctl daemon-reload
systemctl restart docker
systemctl start libvirtd

[ "$skip_build_image" = "true" ] && docker_load_images
